#!usr/bin/env python
#coding=utf8

import os

from django.http import Http404, HttpResponse
from django.utils import simplejson
from django.db import transaction

from tuangou.common_logic.template import render_to_response, static_file
from tuangou.common_logic.exception_mgr import log_except
from tuangou.business_logic import bi_item, bi_category, bi_tuangou, bi_appform, bi_hotitem, bi_systemkeyvalue, bi_systemkeyvalue, bi_cooperation
from tuangou import config
from tuangou.common_logic import commutil
from forms import AppFormForm, FeedbackForm

def index(request, order_by):
    '''
    首页
    @order_by: 直接在url配置中指定，不用过滤
    '''
    try:
        page = int(request.GET.get('page',1))
    except:
        page = 1
    page_size  = config.PAGE_SIZE
    items = bi_item.get_item_list(page, page_size, order_by)
    item_count = bi_item.get_item_count()
    hots = bi_hotitem.get_hotitem_to_index()
    menuCategorys = bi_category.get_menu_category()
    r_dict = {'items': items, 'order_by':order_by, 'category_type':'item', 'total_count':item_count, 'page':page, 'page_size':page_size, 'hots':hots, 'menuCategorys':menuCategorys}

    return render_to_response('tuan/index.html', r_dict, request)

def indexpage(request):
    keyvalue = bi_systemkeyvalue.get_by_key("company_publicity_pictures")
    platforms = bi_cooperation.get_platform_home_list()
    brands = bi_cooperation.get_brand_home_list()
    r_dict = {'imgurl': keyvalue.value, 'platforms':platforms, 'brands':brands}
    
    return render_to_response('tuan/index_page.html', r_dict, request)

def product_detail(request, product_id):
    item = bi_item.get_item_by_id(product_id)
    hots = bi_hotitem.get_hotitem_to_index()
    menuCategorys = bi_category.get_menu_category()
    r_dic = {'item': item, 'category_type':'item', 'itemimages' : item.itemimage_set.all(), 'hots':hots, 'menuCategorys':menuCategorys} 
    return render_to_response('tuan/detail.html', r_dic, request)

def get_list_by_category(request, category_id, category_type='item'):

    if category_type=='item':
        r_dict = get_item_list_by_category(request, category_id)
        return render_to_response('tuan/index.html', r_dict, request)
    elif category_type=='tuan':
        r_dict = get_tuan_list_by_category(request, category_id)
        return render_to_response('tuan/tuaninfo.html', r_dict, request)

def get_item_list_by_category(request, category_id):
    try:
        page = int(request.GET.get('page',1))
        order_by = request.GET.get('order_by','-createdtime')
    except:
        page = 1
    page_size  = config.PAGE_SIZE

    category = bi_category.get_category_by_id(category_id)
    items = []
    item_count = 0
    if category:
        if category.level==1:
            items, item_count = bi_category.get_item_list_by_top_category(category, page, page_size, order_by)
        else:
            items = bi_category.get_item_list_by_category(category, page, page_size, order_by)
            item_count = bi_category.get_item_by_category_count(category)
    hots = bi_hotitem.get_hotitem_to_index()
    menuCategorys = bi_category.get_menu_category()
    r_dict = {'items': items, 'order_by':order_by, 'category_type':'item', 'total_count':item_count, 'page':page, 'page_size':page_size, 'hots':hots, 'menuCategorys':menuCategorys }

    return r_dict

def get_tuan_list_by_category(request, category_id):
    try:
        page = int(request.GET.get('page',1))
        order_by = request.GET.get('order_by','-tuan_saledate')
    except:
        page = 1
    page_size  = config.PAGE_SIZE

    category = bi_category.get_category_by_id(category_id)
    tuans = []
    tuan_count = 0
    if category:
        tuans, tuan_count = bi_tuangou.get_itemtuangou_list_by_category(category, page, page_size, order_by)
    hots = bi_hotitem.get_hotitem_to_index()
    menuCategorys = bi_category.get_menu_category()
    r_dict = {'tuans': tuans, 'order_by':order_by, 'category_type':'tuan', 'total_count':tuan_count, 'page':page, 'page_size':page_size, 'hots':hots, 'menuCategorys':menuCategorys }

    return r_dict

def tuan_index(request, order_by):
    '''
    团购
    '''
    try:
        page = int(request.GET.get('page',1))
    except:
        page = 1
    page_size  = config.PAGE_SIZE
    
    tuans = bi_tuangou.get_itemtuangou_list(page, page_size, order_by)
    tuan_count = bi_tuangou.get_tuan_count()
    hots = bi_hotitem.get_hotitem_to_index()
    menuCategorys = bi_category.get_menu_category()
    r_dict = {'tuans': tuans, 'order_by':order_by, 'category_type':'tuan', 'total_count':tuan_count, 'page':page, 'page_size':page_size, 'hots':hots, 'menuCategorys':menuCategorys }

    return render_to_response('tuan/tuaninfo.html', r_dict, request)

def tuan_detail(request, tuan_id):
    tuan = bi_tuangou.get_itemtuangou_by_id(tuan_id)
    hots = bi_hotitem.get_hotitem_to_index()
    menuCategorys = bi_category.get_menu_category()
    r_dic = {'tuan': tuan , 'category_type':'tuan', 'itemimages' : tuan.item.itemimage_set.all(), 'hots':hots, 'menuCategorys':menuCategorys} 
    return render_to_response('tuan/tuan_detail.html', r_dic, request)

def tuan_list_by_item_id(request, product_id, order_by):
    '''
    根据商品ID获取团购信息
    '''
    try:
        page = int(request.GET.get('page',1))
    except:
        page = 1
    page_size  = config.PAGE_SIZE

    item = bi_item.get_item_by_id(product_id)

    tuans = []
    tuan_count = 0
    if item:
        tuans, tuan_count = bi_tuangou.get_itemtuan_list_by_item_id(item, page, page_size, order_by)
    hots = bi_hotitem.get_hotitem_to_index()
    menuCategorys = bi_category.get_menu_category()
    r_dict = {'tuans': tuans, 'order_by':order_by, 'category_type':'tuan', 'total_count':tuan_count, 'page':page, 'page_size':page_size, 'hots':hots, 'menuCategorys':menuCategorys }

    return render_to_response('tuan/tuaninfo.html', r_dict, request)

def about_us(request):
    hots = bi_hotitem.get_hotitem_to_index()
    menuCategorys = bi_category.get_menu_category()
    keyvalue = bi_systemkeyvalue.get_by_key('about_us')
    return render_to_response('site_info/about_us.html', {'category_type':'item', 'hots':hots, 'menuCategorys':menuCategorys, 'value':keyvalue.value}, request)
def contact_us(request):
    hots = bi_hotitem.get_hotitem_to_index()
    menuCategorys = bi_category.get_menu_category()
    keyvalue = bi_systemkeyvalue.get_by_key('contact_us')
    return render_to_response('site_info/contact_us.html', {'category_type':'item', 'hots':hots, 'menuCategorys':menuCategorys, 'value':keyvalue.value}, request)
def join_us(request):
    hots = bi_hotitem.get_hotitem_to_index()
    menuCategorys = bi_category.get_menu_category()
    keyvalue = bi_systemkeyvalue.get_by_key('join_us')
    return render_to_response('site_info/join_us.html', {'category_type':'item', 'hots':hots, 'menuCategorys':menuCategorys, 'value':keyvalue.value}, request)
def co_application(request):
    hots = bi_hotitem.get_hotitem_to_index()
    menuCategorys = bi_category.get_menu_category()
    return render_to_response('site_info/co_application.html', {'category_type':'item', 'hots':hots, 'menuCategorys':menuCategorys}, request)

@transaction.commit_on_success
def save_co_application(request):
    '''
    保存合作信息
    '''
    r_dict = {'success': False}
    form = AppFormForm(request.POST)
    if form.is_valid():
        try:
            movie = bi_appform.save_appform(**form.cleaned_data)
            r_dict['success'] = True
            transaction.commit()
        except Exception, e:
            transaction.rollback()
            if hasattr(e, 'messages'):
                r_dict['err_msg'] = ', '.join(e.messages)
            else:
                r_dict['err_msg'] = str(e)
    else:
        r_dict['err_msg'] = commutil.get_form_error_msg(form)
    
    return HttpResponse(simplejson.dumps(r_dict))

def feedback(request):
    hots = bi_hotitem.get_hotitem_to_index()
    menuCategorys = bi_category.get_menu_category()
    return render_to_response('site_info/feedback.html', {'category_type':'item', 'hots':hots, 'menuCategorys':menuCategorys}, request)

@transaction.commit_on_success
def save_feedback(request):
    '''
    保存反馈信息
    '''
    
    r_dict = {'success': False}
    form = FeedbackForm(request.POST)
    if form.is_valid():
        try:
            movie = bi_appform.save_feedback(**form.cleaned_data)
            r_dict['success'] = True
            transaction.commit()
        except Exception, e:
            transaction.rollback()
            if hasattr(e, 'messages'):
                r_dict['err_msg'] = ', '.join(e.messages)
            else:
                r_dict['err_msg'] = str(e)
    else:
        r_dict['err_msg'] = commutil.get_form_error_msg(form)
    
    return HttpResponse(simplejson.dumps(r_dict))

def search(request, keyword):
    try:
        page = int(request.GET.get('page',1))
    except:
        page = 1
    page_size  = config.PAGE_SIZE
    order_by = '-createdtime'
    items = bi_item.search_item_list(keyword, page, page_size, order_by)
    item_count = bi_item.search_item_count(keyword)
    hots = bi_hotitem.get_hotitem_to_index()
    menuCategorys = bi_category.get_menu_category()
    r_dict = {'keyword':keyword, 'items': items, 'order_by':order_by, 'category_type':'item', 'total_count':item_count, 'page':page, 'page_size':page_size, 'hots':hots, 'menuCategorys':menuCategorys }

    return render_to_response('tuan/search.html', r_dict, request)

def platform(request):
    '''
    合作平台
    '''
    platforms = bi_cooperation.get_platform_list()
    r_dict = {'platforms': platforms}

    return render_to_response('tuan/cooperationplatform.html', r_dict, request)

def brand(request):
    '''
    合作品牌
    '''
    brands = bi_cooperation.get_brand_list()
    r_dict = {'brands': brands}

    return render_to_response('tuan/cooperationbrand.html', r_dict, request)

def my_custom_404_view(request):
    return render_to_response('404.html', {'category_type':'item'}, request)

def my_custom_500_view(request):
    log_except(config.ERROR_LOG_PATH)
    return render_to_response('500.html', {'category_type':'item'}, request)

